/**
 * 一个简单的死锁类
 * * 当DeadLock类的对象flag==1时（td1），先锁定o1,睡眠500毫秒
 * * 而td1在睡眠的时候另一个flag==0的对象（td2）线程启动，先锁定o2,睡眠500毫秒
 * * td1睡眠结束后需要锁定o2才能继续执行，而此时o2已被td2锁定；
 * * td2睡眠结束后需要锁定o1才能继续执行，而此时o1已被td1锁定；
 * * td1、td2相互等待，都需要得到对方锁定的资源才能继续执行，从而死锁。
 */
public class deadLock implements Runnable{
    public static void main(String[] args) {
        deadLock t1 = new deadLock();
        deadLock t2 = new deadLock();

        t1.flag = 1;
        t2.flag = 0;

        new Thread(t1).start();
        new Thread(t2).start();


    }

    public int flag = 1;
    private static Object object1 = new Object();
    private static Object object2 = new Object();

    @Override
    public void run() {
        System.out.println("flag" + flag);
        if (flag == 1){
            synchronized (object1){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (object2){
                    System.out.println("1");
                }

            }
        }

        if (flag == 0){
            synchronized (object2){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (object1){
                    System.out.println("0");
                }

            }
        }

    }
}
